package com.miracle.system.service;

import javax.annotation.Resource;

import com.miracle.core.security.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import com.miracle.core.security.domain.SecurityUserDetails;

/**
 * 登录校验方法
 *
 * @author miracle
 */
@Component
public class SysLoginService
{
    @Autowired
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid)
    {
        // 用户验证
        Authentication authentication = null;
        try
        {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        SecurityContextHolder.getContext().setAuthentication(authentication);
        SecurityUserDetails securityUserDetails = (SecurityUserDetails) authentication.getPrincipal();
        // 生成token
        return tokenService.createToken(securityUserDetails);
    }
}
